// src/utils/auth.js

import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import axios from '@/utils/axios.js';
export const userInfo = ref(null);

export const checkTokenAndFetchUserInfo = async () => {
    const token = localStorage.getItem('token');
    const tokenExpireTime = localStorage.getItem('tokenExpireTime');

    if (token && tokenExpireTime && Date.now() < tokenExpireTime) {
        try {
            const response = await axios.get('/app/user/info/person', {
                headers: {
                    Authorization: `${token}`,
                },
            });
            userInfo.value = response.data.data;
            console.log('checkTokenAndFetchUserInfo', userInfo.value);

        } catch (error) {
            ElMessage({
                message: '获取用户信息失败，请重新登录',
                type: 'error',
            });
            localStorage.removeItem('token');
            localStorage.removeItem('tokenExpireTime');
            userInfo.value = null;
        }
    }
};

// 如果所有字段都不为空，返回 true，否则返回 false
export const validateUserInfo = () => {
    console.log('validateUserInfo', userInfo.value);
    const requiredFields = ['userName', 'contactName', 'contactPhone', 'address', 'email'];

    return requiredFields.every(field => {
        return userInfo.value[field] !== undefined && userInfo.value[field] !== null && userInfo.value[field].trim() !== '';
    });
};

export const logout = () => {
    try {
        localStorage.removeItem('token');
        localStorage.removeItem('tokenExpireTime');
        localStorage.removeItem('refreshToken');
        localStorage.removeItem('refreshTokenExpireTime');

        userInfo.value = null;

        localStorage.removeItem('formData');
        localStorage.removeItem('imgList');

        ElMessage({
            message: '已退出登录',
            type: 'success',
        });
    } catch (error) {
        ElMessage({
            message: '退出登录失败',
            type: 'error',
        });
        throw new Error(error);
    }


};

